package git.soulbgm.common.socket;

import git.soulbgm.common.Constant;
import git.soulbgm.utils.ByteUtil;
import git.soulbgm.utils.LogUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.DefaultThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author 贺瑞杰
 * @version V1.0
 * @date 2018-10-18 9:22
 * @description
 */
public class TcpClient implements Runnable {

    private LogUtil log = new LogUtil(getClass());

    /**
     * TCP客户端连接服务器的IP
     */
    private String tcpHost;
    /**
     * TCP客户端连接服务的端口
     */
    private int tcpPort;
    /**
     * TCP传输数据的线程数
     */
    private int tcpWorkerThreadNumber;

    /**
     * 管理传输数据线程组
     */
    private EventLoopGroup workGroup;

    /**
     * 传输管道
     */
    private static Channel channel;

    private Bootstrap bootstrap;

    private ThreadPoolExecutor threadPool;

    private static TcpClient tcpClient;

    private ChannelInboundHandlerAdapter tcpClientHandle;

    private TcpClient() {
    }

    private void setParm(String tcpHost, int tcpPort, int tcpWorkerThreadNumber) {
        this.tcpHost = tcpHost;
        this.tcpPort = tcpPort;
        this.tcpWorkerThreadNumber = tcpWorkerThreadNumber;
    }

    /**
     * 开启TCP客户端
     *
     * @param tcpClientHandle TCP处理数据的handle
     */
    public void start(ChannelInboundHandlerAdapter tcpClientHandle) {
        this.tcpClientHandle = tcpClientHandle;
        ThreadFactory threadFactory = new DefaultThreadFactory("tcpClient");
        threadPool = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1024), threadFactory, new ThreadPoolExecutor.AbortPolicy());
        threadPool.execute(this);
    }

    /**
     * 单例模式
     * 获得TcpClient
     *
     * @param tcpHost 信服的IP
     * @param tcpPort 信服的端口
     * @return UDP服务端
     */
    public static TcpClient getTcpClient(String tcpHost, int tcpPort) {
        return getTcpClient(tcpHost, tcpPort, 3);
    }

    /**
     * 单例模式
     * 获得TcpClient
     *
     * @param tcpHost               TCP服务器的IP
     * @param tcpPort               TCP服务器的端口
     * @param tcpWorkerThreadNumber TCP传输数据所用线程数
     * @return UDP服务端
     */
    public static TcpClient getTcpClient(String tcpHost, int tcpPort, int tcpWorkerThreadNumber) {
        tcpClient = Singleton.INSTANCE.getTcpClient();
        tcpClient.setParm(tcpHost, tcpPort, tcpWorkerThreadNumber);
        return tcpClient;
    }

    @Override
    public void run() {
        workGroup = new NioEventLoopGroup(tcpWorkerThreadNumber);
        bootstrap = new Bootstrap()
                .group(workGroup)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline()
                                /*
                                    第一个参数 60 表示读操作空闲时间
                                    第二个参数 20 表示写操作空闲时间
                                    第三个参数 60*10 表示读写操作空闲时间
                                    第四个参数 单位/秒
                                 */
//                                .addLast(new IdleStateHandler(60, 20, 60 * 10, TimeUnit.SECONDS))
                                .addLast(new DelimiterBasedFrameDecoder(2048, ByteUtil.byteArrayToByteBuf(ByteUtil.stringToByteArray(Constant.TCP_DELIMITER))))
                                .addLast(tcpClientHandle)
                                .addLast(new StringEncoder());
                    }
                });
        doConnect();
    }

    public void doConnect() {
        if (channel != null && channel.isActive()) {
            return;
        }
        try {
            ChannelFuture future = bootstrap.connect(tcpHost, tcpPort).sync();
            future.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        channel = future.channel();
                        log.info("tcp client start-up");
                    }
                }
            });
            channel = future.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("tcp client connect {}:{} fail", tcpHost, tcpPort, e);
        }
    }

    public void destroy() {
        workGroup.shutdownGracefully().syncUninterruptibly();
        threadPool.shutdown();
        log.info("close tcp client success");
    }

    public static boolean sendMsg(byte[] data) {
        data = ByteUtil.byteMergerAll(data, Constant.TCP_DELIMITER_BYTE);
        channel.writeAndFlush(ByteUtil.byteArrayToByteBuf(data));
        return true;
    }

    private enum Singleton {
        INSTANCE;

        private TcpClient tcpClient;

        /**
         * JVM保证这个方法决对只调用一次
         */
        Singleton() {
            tcpClient = new TcpClient();
        }

        public TcpClient getTcpClient() {
            return tcpClient;
        }
    }
}
